"""
-*- coding: utf-8 -*-
@Author  : Link
@Time    : 2022/5/12 13:54
@Software: PyCharm
@File    : table_module.py
@Remark  : 
"""

from pyqtgraph import TableWidget
from PySide2 import QtCore, QtWidgets, QtGui

translate = QtCore.QCoreApplication.translate


class PauseTableWidget(TableWidget):

    def __init__(self, *args, **kwds):
        super(PauseTableWidget, self).__init__(*args, **kwds)

        self.contextMenu.addAction(translate("PauseTableWidget", 'Paste')).triggered.connect(self.paste)

    def paste(self):
        """
        将剪切板的数据复制到TableWidget中
        先找到选中的行列位置
        再根据数据来进行黏贴
        """
        text = QtWidgets.QApplication.clipboard().text()  # type:str
        text_rows = text.split('\n')[1:-1]
        selection = self.selectedRanges()
        if not selection:
            return
        selection = selection[0]
        select_row = selection.topRow()
        select_column = selection.leftColumn()

        pause_row = len(text_rows)
        for i in range(pause_row):
            item_row = i + select_row
            row_split_text = text_rows[i].split('\t')
            for j in range(len(row_split_text)):
                item_column = select_column + j
                item = self.item(item_row, item_column)  # type:QtWidgets.QTableWidgetItem
                if item is None:
                    continue
                item.setText(row_split_text[j])

    def keyPressEvent(self, ev):
        if ev.matches(QtGui.QKeySequence.StandardKey.Paste):
            ev.accept()
            self.paste()
        else:
            super().keyPressEvent(ev)
